package com.liangzhong.modules.login.mediator
{
	import com.common.stdlib.DateUtil;
	import com.common.utils.DisplayObjectUtil;
	import com.common.utils.Reflection;
	import com.common.utils.Stats;
	import com.global.GlobalDef;
	import com.liangzhong.constants.ApplicationConstants;
	import com.liangzhong.constants.NotificationConstants;
	import com.liangzhong.constants.ResourceConst;
	import com.liangzhong.events.AppEventDispatcher;
	import com.liangzhong.events.FriendEvent;
	import com.liangzhong.events.LoginEvent;
	import com.liangzhong.events.MainEvent;
	import com.liangzhong.events.NotifierEvent;
	import com.liangzhong.manager.ResourceManager;
	import com.liangzhong.mediator.BaseMediator;
	import com.liangzhong.message.http.JsClient;
	import com.liangzhong.model.AppData;
	import com.liangzhong.model.login.LoginAwardVo;
	import com.liangzhong.model.login.SignInfoVo;
	import com.liangzhong.modules.Main.Mediator.CommonMediator;
	import com.liangzhong.modules.Main.Mediator.EffectMediator;
	import com.liangzhong.modules.Main.Mediator.LogicMediator;
	import com.liangzhong.modules.Main.Mediator.MainMediator;
	import com.liangzhong.modules.guide.mediator.GuideMediator;
	import com.lz.football.module.base.IModuleView;
	import com.lz.football.module.friend.ILookUpView;
	import com.lz.football.module.login.ILoginAwardView;
	import com.lz.football.module.login.ILoginSignView;
	
	import flash.display.DisplayObject;
	import flash.display.DisplayObjectContainer;
	import flash.display.MovieClip;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.utils.setTimeout;
	
	import lz.controls.Alert;
	import lz.controls.managers.AnimationManager;
	import lz.controls.managers.PopUpManager;
	
	import org.puremvc.as3.interfaces.INotification;

	/**
	 *登录 mediator 
	 * @author lxh
	 * 
	 */	
	public class LoginMediator extends BaseMediator
	{
		public static const MediatorName :String = "LoginMediator";
		/**
		 * 登陆成功
		 */		
		public static const Login_Login_Success :String = "Login_Login_Success";
		/**
		 * 登陆失败
		 */		
		public static const Login_Login_Failed  :String = "Login_Login_Failed";
		/**
		 *登录奖励信息  res
		 */		
		public static const Login_AwardInfo_Result	:String = "LoginMediator/Login_AwardInfo_Result";
		/**
		 *获取奖励 res 
		 */		
		public static const Login_GetAward_Result	:String = "LoginMediator/Login_GetAward_Result";
		/**
		 *用户请求server 的时候 用来蒙住界面 防止用户多次请求 
		 */		
		private var serverReqShapeMark :Sprite;
		
		
		public function LoginMediator(mediatorName:String=null, viewComponent:Object=null)
		{
			super(mediatorName, viewComponent);
		}
		/**
		 *获取 实例 
		 * @return 
		 * 
		 */		
		public function get loginView():DisplayObjectContainer
		{
			return viewComponent as DisplayObjectContainer;
		}
		/**
		 *添加事件 
		 * 
		 */		
		override public function addEventListeners():void
		{
			AppEventDispatcher.getInstance().addEventListener(NotificationConstants.Application_Show_Req_Mark,addReqMark);
			AppEventDispatcher.getInstance().addEventListener(NotificationConstants.Application_Un_Show_Req_Mark,removeReqMark);
			AppEventDispatcher.getInstance().addEventListener(LoginEvent.GET_LOGIN_AWARD,getLoginAward);
			AppEventDispatcher.getInstance().addEventListener(MainEvent.Open_Sign_View,onOpenSignViewHandler);
			AppEventDispatcher.getInstance().addEventListener(LoginEvent.USER_SIGN,userSignHandler);
			AppEventDispatcher.getInstance().addEventListener(LoginEvent.USER_RESIGN,userReSignHandler);
			AppEventDispatcher.getInstance().addEventListener(LoginEvent.USER_GET_SIGN_AWARD,userGetSignAwardHandler);
			AppEventDispatcher.getInstance().addEventListener(LoginEvent.USER_GET_QZONE_VIP_AWARD,userGetQzoneAwardHandler);
			
			AppEventDispatcher.getInstance().addEventListener(FriendEvent.CANCEL_CHALLENGE_FRIEND,cancelChallengeHandler);
			AppEventDispatcher.getInstance().addEventListener(FriendEvent.CHALLENGE_FRIEND,onChallengeHandler);
			GlobalDef.GameStage.addEventListener(Event.RESIZE,onResizeHandler);
		}
		
		protected function onChallengeHandler(event:FriendEvent):void
		{
			this.sendNotification(ApplicationConstants.FRIEND_CHALLENGE,event.param);
		}
		/**
		 *舞台大小改变 
		 * @param e
		 * 
		 */		
		private function onResizeHandler(e :Event):void
		{
			serverReqShapeMark.graphics.clear();
			serverReqShapeMark.graphics.beginFill(0x123456,.1);
			serverReqShapeMark.graphics.drawRect(0, 0, GlobalDef.GameStage.stageWidth, GlobalDef.GameStage.stageHeight);
			serverReqShapeMark.graphics.endFill();
			DisplayObjectUtil.removeAllChildren(serverReqShapeMark);
			var reqMc :MovieClip = Reflection.createInstance("com.lz.res.RequestLoadMC");
			if(reqMc)
			{
				serverReqShapeMark.addChild(reqMc);
				reqMc.x = (GlobalDef.GameStage.stageWidth - reqMc.width)>>1;
				reqMc.y = ((GlobalDef.GameStage.stageHeight - reqMc.height)>>1) - 100;
			}
		}
		/**
		 *取消挑战好友 
		 * @param event
		 * 
		 */
		protected function cancelChallengeHandler(event:FriendEvent):void
		{
			this.sendNotification(ApplicationConstants.FRIEND_CANCEL_CHALLENGE,event.param);
		}
		/**
		 *加载完成 
		 * 
		 */		
		private function onLoaderComplete():void
		{
			onLogin();
		}
		/**
		 * 连接成功
		 */		
		private function onConnectSuccess():void
		{
			//onLogin();
			if(GlobalDef.Platform_Code == 1)
			{
				this.sendNotification(ApplicationConstants.Login_TGW);
			}
			setTimeout(onLogin,50);
		}
		/**
		 *登陆成功 
		 * 
		 */	
		private function loginSuccess():void
		{
			DisplayObjectUtil.removeAllChildren(loginView);
			//注册mediator
			facade.registerMediator(new LogicMediator(LogicMediator.MediatorName));//一般逻辑
			facade.registerMediator(new MainMediator(MainMediator.MediatorName));//主界面
			facade.registerMediator(new CommonMediator(CommonMediator.MediatorName));//通用
			facade.registerMediator(new EffectMediator(EffectMediator.MediatorName));//效果
			facade.registerMediator(new GuideMediator(GuideMediator.MediatorName));//引导
		}
		/**
		 *登陆失败
		 * 
		 */		
		private function loginFailed():void
		{
			showRemindInfo("登陆错误");
		}
		/**
		 *登陆 
		 */		
		private function onLogin():void
		{
			var uid :uint = AppData.getInstance().user.uid;
			var sid :String = AppData.getInstance().user.key;
			if(AppData.getInstance().isLoadComplete && AppData.getInstance().isConnect)
			{
				this.sendNotification(ApplicationConstants.Login_login,{userId:uid,userKey:sid});
			}
		}
		/**
		 *显示提示信息 
		 * @param value
		 * 
		 */		
		private function showRemindInfo(value:String):void
		{
			Alert.show(value,"",Alert.YES,GlobalDef.GameStage);
		}
		/**
		 * 监听信息
		 * @return 
		 * 
		 */		
		override public function listNotificationInterests():Array
		{
			return [NotificationConstants.Login_Loader_Complete,
				NotificationConstants.Login_Connect_Server_Success,
				NotificationConstants.Login_Server_Close,
				Login_Login_Success,
				Login_Login_Failed,
				NotificationConstants.Application_Show_RemindInfo,
				NotificationConstants.Update_UserDetailInfo,
				NotificationConstants.Application_Show_Req_Mark,
				NotificationConstants.Application_Un_Show_Req_Mark,
				Login_AwardInfo_Result,
				Login_GetAward_Result,
				NotificationConstants.GUIDE_START,
				NotificationConstants.GUIDE_FINISH,
				NotificationConstants.LOOK_UP_INFO,
				NotificationConstants.FRIEND_CHANGLLE_TIME];
		}
		/**
		 * 处理信息
		 * @param notification
		 * 
		 */		
		override public function handleNotification(notification:INotification):void
		{
			var loginAwardVo :LoginAwardVo;
			switch(notification.getName())
			{
				case NotificationConstants.Login_Loader_Complete://加载完成
				{
					onLoaderComplete();
					break;
				}
				case NotificationConstants.Login_Connect_Server_Success://连接成功
				{
					onConnectSuccess();
					break;
				}
				case Login_Login_Success://登陆成功
				{
					loginSuccess();
					break;
				}
				case Login_Login_Failed://登陆失败
				{
					loginFailed();
					break;
				}	
				case NotificationConstants.Application_Show_RemindInfo://提示信息
				{
					showRemindInfo(notification.getBody() + "");
					break;
				}
				case NotificationConstants.Login_Server_Close://服务关闭
				{
					Alert.show("与服务器断开连接","",Alert.YES,GlobalDef.GameStage,serverCloseHandler);
					break;
				}
				case NotificationConstants.Application_Show_Req_Mark://蒙板
				{
					addReqMark();
					break;
				}
				case NotificationConstants.Application_Un_Show_Req_Mark://移除蒙板
				{
					removeReqMark();
					break;
				}
				case Login_AwardInfo_Result://登录奖励信息  res
				{
					loginAwardVo = notification.getBody() as LoginAwardVo;
					/*if(loginAwardVo.flag == 0)
					{
						AnimationManager.addItem({func:showAwardInfoView,data:loginAwardVo});
					}*/
					//showAwardInfoView(loginAwardVo);
					break;
				}
				case Login_GetAward_Result://获取奖励 res 
				{
					showLoginAwardView();
					break;
				}
				case NotificationConstants.GUIDE_START://引导开始
				{
					DisplayObjectUtil.removeAllChildren(loginView);
					break;
				}
				case NotificationConstants.GUIDE_FINISH://引导完成
				{
					DisplayObjectUtil.removeAllChildren(loginView);
					//this.sendNotification(ApplicationConstants.Login_Get_Login_Award);
					break;
				}
				case NotificationConstants.LOOK_UP_INFO:
					showLookUpInfo(notification.getBody());
					AppEventDispatcher.getInstance().dispatchEvent(new FriendEvent(FriendEvent.GET_LOOK_UP_INFO));
					break;
				case NotificationConstants.FRIEND_CHANGLLE_TIME:
					if(_lookView != null && (_lookView as DisplayObjectContainer).parent)
					{
						_lookView.showChanglleTime();
					}
					break;
			}
		}
		private var _lookView:ILookUpView;
		private function showLookUpInfo($obj:Object):void
		{
			if(_lookView == null)
			{
				_lookView = Reflection.createInstance("com.lz.football.module.friend.LookUpInfoView");
				(_lookView as IModuleView).initUI();
			}
			_lookView.showInfo($obj);
			GlobalDef.AlertContainer.addChild(_lookView as DisplayObject);
		}
		/**
		 * 服务器断开连接
		 * @param mode
		 * 
		 */		
		private function serverCloseHandler(mode :int):void
		{
			JsClient.app_reload();
		}
		/**
		 *打开签到界面
		 * @param e
		 */		
		private var loginSingView :ILoginSignView;
		private function onOpenSignViewHandler(e :MainEvent):void
		{
			var signInfoVo :SignInfoVo = AppData.getInstance().user.signInfoVo;
			if(signInfoVo == null)
			{
				return;
			}
			if(loginSingView && loginSingView["parent"])
			{
				return;
			}
			loginSingView = Reflection.createInstance("com.lz.football.module.sign.view.LoginSignView");
			if(loginSingView)
			{
				loginSingView.data = signInfoVo;
				loginSingView.initUI();
				PopUpManager.addPopUp(loginSingView as DisplayObject,GlobalDef.GameWindowContainer,GlobalDef.GameStage.stageWidth,GlobalDef.GameStage.stageWidth,false);
				//@lake 2013-12-05 Guide use
				if(Reflection.createInstance("com.lz.res.LoginSignView"))
				{
					AppEventDispatcher.getInstance().dispatchEvt(NotifierEvent.MODULE_LOAD_RES_COMPLETE);
				}
			}
		}
		/**
		 *用户签到 
		 * @param e
		 * 
		 */		
		private function userSignHandler(e :Event):void
		{
			this.sendNotification(ApplicationConstants.Login_User_Sign);
		}
		/**
		 *用户补签 
		 * @param e
		 * 
		 */		
		private function userReSignHandler(e :Event):void
		{
			this.sendNotification(ApplicationConstants.Login_User_Resign);
		}
		/**
		 *获取签到奖励  
		 * @param e
		 * 
		 */		
		private function userGetSignAwardHandler(e :LoginEvent):void
		{
			this.sendNotification(ApplicationConstants.Login_User_Get_Sign_Award,e.param);
		}
		/**
		 *获取黄钻礼包 
		 * @param e
		 * 
		 */		
		private function userGetQzoneAwardHandler(e :LoginEvent):void
		{
			this.sendNotification(ApplicationConstants.Login_User_Get_Qzone_Vip_Award,e.param);
		}
		/**
		 *显示登录奖励面板 
		 * @param loginAwardVo
		 * 
		 */		
		private function showAwardInfoView():void
		{
			var loginAwardView :ILoginAwardView = Reflection.createInstance("com.lz.football.module.login.view.LoginAwardView");
			if(loginAwardView)
			{
				loginAwardView.initUI();
				loginAwardView.data = null;
				PopUpManager.addWindow(loginAwardView as DisplayObject,GlobalDef.GameStage,0,0,true);
			}
		}
		/**
		 *获取登录奖励 
		 * 
		 */		
		private function getLoginAward(e :NotifierEvent):void
		{
			AppEventDispatcher.getInstance().removeEventListener(LoginEvent.GET_LOGIN_AWARD,getLoginAward);
			this.sendNotification(ApplicationConstants.Login_Get_Login_Award);
		}
		/**
		 * 添加蒙板
		 * 
		 */		
		private function addReqMark(e :Event = null):void
		{
			AppData.getInstance().markCount++;
			GlobalDef.GameStage.addChild(serverReqShapeMark);
		}
		/**
		 * 移除蒙板
		 * 
		 */		
		private function removeReqMark(e :Event = null):void
		{
			if(AppData.getInstance().markCount > 0)
			{
				AppData.getInstance().markCount--;
			}
			if(AppData.getInstance().markCount == 0 && serverReqShapeMark.parent)
			{
				serverReqShapeMark.parent.removeChild(serverReqShapeMark);
			}
		}
		/**
		 *显示登录奖励 
		 * 
		 */		
		public function showLoginAwardView():void
		{
			//判断活动期间 登录奖励面板显示
			var startDate 	:Date = new Date("06/06/2013");//开始日期
			var endDate 	:Date = new Date("06/23/2013");//结束日期
			var curDate 	:Date = new Date(AppData.getInstance().time * 1000);
			if(DateUtil.betweenTwoDate(curDate,startDate,endDate))
			{
				AnimationManager.addItem({func:showAwardInfoView});
			}
		}
		/**
		 * 
		 * 注册
		 */		
		override public function onRegister():void
		{
			addEventListeners();
			serverReqShapeMark = new Sprite();
			serverReqShapeMark.graphics.beginFill(0x123456,.1);
			serverReqShapeMark.graphics.drawRect(0, 0, GlobalDef.StageWidth, GlobalDef.StageHeight);
			serverReqShapeMark.graphics.endFill();
			var reqMc :MovieClip = Reflection.createInstance("com.lz.res.RequestLoadMC");
			if(reqMc)
			{
				serverReqShapeMark.addChild(reqMc);
				reqMc.x = (GlobalDef.StageWidth - reqMc.width)>>1;
				reqMc.y = ((GlobalDef.StageHeight - reqMc.height)>>1) - 100;
			}
			GlobalDef.GameContainer = new Sprite();;
			GlobalDef.GameStage.addChild(GlobalDef.GameContainer);
			GlobalDef.GameWindowContainer = new Sprite();
			GlobalDef.GameStage.addChild(GlobalDef.GameWindowContainer);
			GlobalDef.AlertContainer = new Sprite();
			GlobalDef.GameStage.addChild(GlobalDef.AlertContainer);
			if(loginView && loginView.contextMenu)
			{
				loginView.contextMenu.hideBuiltInItems();
			}
			//过滤词
			var filterConfig :XML = ResourceManager.instance.getResource(ResourceConst.FILTER_WORD_XML);
			var filterwords :Array;
			if(filterConfig)
			{
				filterwords = String(filterConfig.word[0]).split("|");
				GlobalDef.filterWords = filterwords;
			}
			//test
			/*var statusSp :DisplayObject = new Stats();
			GlobalDef.GameStage.addChild(statusSp);
			statusSp.y = 220;*/
		}
	}
}